import { KeyMatchInfo, SELF_KEY_CODE } from "./InputConfig";
/**
 * 键值转换器
 */
export default class InputConverter {
    // private static ins: InputConverter
    // static getInstance() {
    //     if (!this.ins) {
    //         this.ins = new InputConverter();
    //     }
    //     return this.ins;
    // }
    /**
     * key 平台名称
     * key 平台键值
     * value 自定义的键值
     */
    private keyMap: { [key: string]: { [key: number]: string } } = {}

    private selfValueKey: { [key: number]: string } = {}

    protected config: KeyMatchInfo[] = null;

    //不同操作方式对应的映射表
    protected keyCodeMap: { [key: string]: any } = {}

    getKeyName(keyCode: number) {
        return this.selfValueKey[keyCode]
    }

    /**
     * 添加一个平台的键值表
     * @param platform 平台名称 如 cc  steam
     * @param KEY_CODE 按键与键值的对应数据
     */
    addKeyCode(platform: string, KEY_CODE: any) {
        this.keyCodeMap[platform] = KEY_CODE;
        this.setKeyCodeConfig(platform)
    }

    init(config: KeyMatchInfo[]) {
        this.config = config;

        for (const platform in this.keyCodeMap) {
            this.setKeyCodeConfig(platform)
        }
    }

    private setKeyCodeConfig(platform: string) {
        let KEY_CODE: any = this.keyCodeMap[platform]
        if (this.config && !this.keyMap[platform] && KEY_CODE) {
            this.keyMap[platform] = {}
            for (const index in this.config) {
                const element = this.config[index];
                let value = this.getKeyValueByKeyName(element.self);
                this.selfValueKey[value] = element.self;
                let list = element[platform];
                for (let k = 0; k < list.length; k++) {
                    const key = KEY_CODE[list[k]];

                    // console.log("InputConverter platform  ", platform, key, element.self)
                    this.keyMap[platform][key] = element.self;
                }
            }
        }
    }

    /**
     * 键值映射，通过平台的key，或者使用的key
     * @param name 平台名称
     * @param key 
     * @returns 
     */
    getKeyValue(name: string, key: number) {
        let data = this.keyMap[name]
        // console.log(' data ', data, key)
        if (data) {
            let id = data[key]
            return this.getKeyValueByKeyName(id)
        } else {
            // console.warn(' data is null ')
        }
        return 0;
    }

    getKeyValueByKeyName(name: string) {
        return SELF_KEY_CODE[name];
    }
}

